<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;


use App\Services\RsaService;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Config\config;

class BaseController extends AbstractController
{

    #[Inject]
    public RsaService $rsaService;

    /**
     * Note - 成功的返回
     * DateTime 2024/8/16 15:46
     * User Admin
     * @param $data
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function return($data = []): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->json([
            'code' => $data['code'] ?? 200,
            'data' => $this->serverEncode($data['data'] ?? []),
            'text' => $data['data'] ?? [],
            'message' => $data['desc'] ?? 'success'
        ])->withStatus($data['status'] ?? 200);

    }

    /**
     * Note - 失败的返回
     * DateTime 2024/8/16 15:45
     * User Admin
     * @param $data
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function fail($data = []): \Psr\Http\Message\ResponseInterface
    {
        return $this->response->json([
            'code' => $data['code'] ?? 500,
            'data' => $this->serverEncode($data['data'] ?? []),
            'message' => $data['desc'] ?? 'fail'
        ])->withStatus($data['status'] ?? 500);
    }


    /**
     * Note - 服务端对返回的数据加密
     * DateTime 2024/8/16 15:45
     * User Admin
     * @param $data
     * @return array|mixed|string
     */
    public function serverEncode($data = [])
    {
        if (empty($data) || config("app_env") != 'prod') {
            return $data;
        }
        $decode = $this->request->post('request_from', 2);
        if ($decode == 2) {
            return $this->rsaService->serverEncode($data);
        }
        return $data;

    }
}
